package com.openarena.model.dao;

import com.openarena.model.Player;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

@ApplicationScoped
@ManagedBean
public class PlayerDAO extends InfArenaDAO {

    private static final Logger logger = Logger.getLogger(PlayerDAO.class.getCanonicalName());

    private static final Map<String,Player> mapIdtoPlayer = new HashMap<String,Player>();

    public PlayerDAO() {
    }

    public Player getPlayerById(String id) {
        if (!mapIdtoPlayer.containsKey(id)) {
            mapIdtoPlayer.put(id, getPlayerById(Integer.valueOf(id)));
        }

        return mapIdtoPlayer.get(id);
    }

    public Player getPlayerById(Integer id) {
        Session session = null;
        try {
            session = getSession();
            return (Player) session.createCriteria(Player.class).add(Restrictions.eq("id", id)).uniqueResult();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
            return null;
        } finally {
            close(session);
        }
    }

    public Player getPlayerByName(String name) {
        Session session = null;
        try {
            session = getSession();
            return (Player) session.createCriteria(Player.class).add(Restrictions.eq("name", name)).uniqueResult();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
            return null;
        } finally {
            close(session);
        }
    }

    public List<Player> getActivePlayers() {
        Session session = null;
        try {
            session = getSession();
            return session.createCriteria(Player.class).add(Restrictions.eq("active", 1)).list();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
            return Collections.EMPTY_LIST;
        } finally {
            close(session);
        }
    }

    public List<Player> getAllPlayers() {
        Session session = null;
        try {
            session = getSession();
            return session.createCriteria(Player.class).addOrder(Order.asc("name")).list();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
            return Collections.EMPTY_LIST;
        } finally {
            close(session);
        }
    }
}
